<template>
  <div class="container">
    <!-- 图层数据 -->
    <div class="layerBtn">
      <img
        :src="layerBtnImg"
        alt=""
        @click="showLayerPanel = !showLayerPanel"
      />
    </div>
    <div class="layerPanel" v-show="showLayerPanel">
      <el-tree
        :data="layerData"
        show-checkbox
        check-on-node-click
        node-key="label"
        default-expand-all
        :render-content="renderLayerContent"
        style="
          width: 100%;
          color: #ffffff;
          font-family: Source Han Sans CN;
          font-weight: medium;
          background-color: transparent;
        "
        @check="handleCheck"
        ref="layerTree"
      >
      </el-tree>
    </div>
  </div>
</template>

<script>
import {
  getReservoir,
  getStation,
  getDzPoint,
  getShPoint,
  getSatellitenephoram,
} from "@/api/layerPanel";
import * as turf from "@turf/turf";
import xinjiangArea from "@/map/新疆.json";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import { Feature } from "ol";
import { Point } from "ol/geom";
import { Stroke, Style, Fill, Circle, Text } from "ol/style";
export default {
  name: "layerPanel",
  data() {
    return {
      layerMap: null,
      lastLayerData: [],
      layerBtnImg: require("@/assets/images/layerBtnGrey.png"),
      showLayerPanel: false,
      layerData: [
        {
          label: "气象",
          children: [
            {
              label: "气象实况",
              children: [
                {
                  label: "气象站点分布图",
                  request: (params) => getStation(params),
                  params: "",
                  addlayer: (res) => {
                    this.stationAdd(res);
                  },
                },
                { label: "降水等值图" },
                { label: "温度" },
                { label: "风速" },
              ],
            },
            { label: "雷达图" },
            {
              label: "云图",
              request: (params) => getSatellitenephoram(params),
              params: "",
              addlayer: (res) => {
                this.cloudAdd(res);
              },
            },
          ],
        },
        {
          label: "水文",
          children: [
            {
              label: "水库",
              request: (params) => getReservoir(params),
              params: "",
              addlayer: (res) => {
                this.reservoirAdd(res);
              },
            },
            { label: "水文站" },
          ],
        },
        {
          label: "普查数据",
          children: [
            {
              label: "高温",
              children: [],
            },
            { label: "大风" },
            { label: "暴雨" },
            { label: "暴雪" },
            { label: "冰雹" },
          ],
        },
        {
          label: "地质灾害",
          children: [
            {
              label: "中小河流隐患点",
            },
            { label: "承灾体" },
            {
              label: "山洪沟隐患点",
              request: (params) => getShPoint(params),
              params: "",
              addlayer: (res) => {
                this.shPointAdd(res);
              },
            },
            { label: "中小河流流域边界" },
            {
              label: "地质灾害隐患点",
              request: (params) => getDzPoint(params),
              params: "",
              addlayer: (res) => {
                this.dzPointAdd(res);
              },
            },
          ],
        },
      ],
    };
  },
  mounted() {
    this.layerMap = this.$store.getters.Map;
  },
  methods: {
    handleCheck(checkedNodes, checked) {
      // ;
      // ;
      //加图层操作
      if (checked.checkedKeys.length > 0) {
        // ;
        //判断新增还是取消
        if (checked.checkedKeys.length > this.lastLayerData.length) {
          // ;
          //新增操作
          let addLayerItem = checked.checkedKeys.filter(
            (item) => !this.lastLayerData.includes(item)
          );
          ;
          //发送请求，添加图层
          let layerRequest = this.findLeafNode(this.layerData, addLayerItem[0]);
          if (layerRequest) {
            ;
            //设置参数,params默认为空,可修改
            // layerRequest.params = {};
            layerRequest.request(layerRequest.params).then((res) => {
              if (res) {
                ;
                layerRequest.addlayer(res.data);
              } else {
                this.$message.error("暂无数据");
              }
            });
          }
        } else {
          ;
          //取消操作
          let delLayerItem = this.lastLayerData.filter(
            (item) => !checked.checkedKeys.includes(item)
          );
          ;
          this.layerMap.map.getAllLayers().forEach((layer) => {
            let name = layer.get("name") || layer.get("layerName");
            if (name == delLayerItem[0]) {
              this.layerMap.map.removeLayer(layer);
            }
          });
        }
      } else {
        ;
        //取消操作
        let delLayerItem = this.lastLayerData.filter(
          (item) => !checked.checkedKeys.includes(item)
        );
        ;
        this.layerMap.map.getAllLayers().forEach((layer) => {
          let name = layer.get("name") || layer.get("layerName");
          if (name == delLayerItem[0]) {
            this.layerMap.map.removeLayer(layer);
          }
        });
      }
      //记录当前选中的图层
      this.lastLayerData = checked.checkedKeys;
    },
    //找叶子节点
    findLeafNode(data, labelToFind) {
      let result = null;
      for (const item of data) {
        if (item.label == labelToFind) {
          // 检查当前项是否为叶子节点（没有children属性或children为空数组）
          if (!item.children || item.children.length === 0) {
            result = item;
            break;
          }
        }
        // 如果当前项有子节点，则递归地在子节点中查找
        if (item.children && item.children.length > 0) {
          let childResult = this.findLeafNode(item.children, labelToFind);
          if (childResult) {
            result = childResult;
            break;
          }
        }
      }
      return result;
    },
    //云图数据
    cloudAdd(res){
      if(res.code != 200){
        this.$message.error('请求失败');
        return;
      }
      const map = this.$store.getters.Map;
      map.map
        .getLayers()
        .getArray()
        .forEach((layer) => {
          if (layer.get("name") == "YunTu-layer") {
            map.map.removeLayer(layer);
          }
        });
      res.data.forEach((item) => {
        //每一张图片对应一个图片图层
        const path = item.path;
        const west = item.west;
        const south = item.south;
        const east = item.east;
        const north = item.north;
        const imageLayer = new Image({
          name: "Leida-layer",
          source: new ImageStatic({
            url: path,
            imageExtent: transformExtent(
              [west,south,east,north],
              "EPSG:3857",
              "EPSG:3857"
            ),
          }),
        });
        imageLayer.setOpacity(0.4)
        imageLayer.setZIndex(20);
        map.map.addLayer(imageLayer);
      });
    },
    //自动站数据
    stationAdd(res) {
      let positions = [];
      let rain = [];
      let names = [];
      ;
      res.forEach((item) => {
        let position = [item.longitude, item.latitude];
        positions.push(position);
        rain.push(item.rain);
        names.push(item.stationname);
      });
      ;
      let source = new VectorSource();
      positions.forEach((position, index) => {
        source.addFeature(
          new Feature({
            geometry: new Point(position),
            weight: rain[index],
            name: names[index],
          })
        );
      });
      let layer;
      layer = new VectorLayer({
        name: "气象站点分布图",
        source: source,
        style: (feature) => {
          return new Style({
            text: new Text({
              offsetX: 0,
              offsetY: 10,
              font: "normal 0.5rem 宋体",
              text: feature.get("name") + "\n",
              fill: new Fill({
                color: "#ffffff",
              }),
              stroke: new Stroke({
                color: "#000000", // 描边颜色，这里是黑色
                width: 2, // 描边宽度，根据需要进行调整
              }),
            }),
          });
        },
      });
      this.layerMap.map.addLayer(layer);
    },
    //水库数据
    reservoirAdd(res) {
      // ;
      res.forEach((item) => {
        ;
        const area = turf.polygon(
          xinjiangArea.features[0].geometry.coordinates
        );
        const flag = turf.booleanPointInPolygon(
          turf.point([item.lgtd, item.lttd]),
          area
        );
        if (!flag) {
          return;
        }
        let legendType;
        if (item.status_difference < 0) {
          legendType = "水库站";
        } else if (item.status_difference >= 0) {
          legendType = "超汛限站";
        }
        let addlayer = this.layerMap.layer.createVectorLayer("水库");
        this.layerMap.marker.addMarker(
          item.lgtd || item.center[0],
          item.lttd || item.center[1],
          addlayer,
          {
            imgUrl: require(`@/assets/lenged/${legendType}.png`),
            scale: 1.5, //大小
            radius: 15,
            pBorderColor: "#000000",
            pBorderWidth: 1,
            pFillColor: "",
          },
          item
        );
      });
    },
    renderLayerContent(h, { node, data, store }) {
      if (
        data.label == "气象" ||
        data.label == "水文" ||
        data.label == "普查数据" ||
        data.label == "地质灾害"
      ) {
        let img = require("@/assets/images/file.png");
        return (
          <span class="button-layer">
            <img src={img} alt="" style={{ width: "25px", height: "20px" }} />
            {node.label}
          </span>
        );
      } else {
        return <span class="button-layer">{node.label}</span>;
      }
    },
  },
  watch: {
    showLayerPanel(newVal) {
      if (newVal) {
        this.layerBtnImg = require("@/assets/images/layerBtnActive.png");
      } else {
        this.layerBtnImg = require("@/assets/images/layerBtnGrey.png");
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.layerBtn {
  position: absolute;
  left: 10px;
  top: 2rem;
  
  img {
    width: 40px;
    height: 40px;
  }
}
.layerPanel {
  position: absolute;
  left: 60px;
  top: 2rem;
  width: 300px;
  height: 700px;
  border: 1px solid #000;
  background-color: rgba(35, 69, 100, 0.7);
  ::v-deep .el-tree-node__content:hover {
    background-color: rgba(1, 79, 115, 0.4);
  }
  ::v-deep .el-tree-node:focus > .el-tree-node__content {
    background-color: transparent;
  }
  ::v-deep .el-tree-node__content > .el-tree-node__expand-icon {
    display: none;
  }
  ::v-deep .el-tree-node__content > label.el-checkbox {
    margin: 0px 5px;
  }
}
</style>
